/**
 * Filename: MemberActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 14:45
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.UUID;

public class PuzzleMakeActivity extends BaseActivity implements View.OnClickListener {
    private ImageView puzzle_make_pic;
    private EditText puzzle_make_edit;
    private String chuanpath;
    private String eventid = "";
    private RelativeLayout puzzle_make;
    private View line_v1;
    private View line_v2;
    private View line_h1;
    private View line_h2;
    private UploadManager mUpManager;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_puzzlemake);
        mUpManager = application.getUploadManager();
        initProgress();
        initView();
        initData();
    }

    private void initView() {
        findViewById(R.id.puzzle_make_back).setOnClickListener(this);
        findViewById(R.id.puzzle_make_share).setOnClickListener(this);
        puzzle_make_pic = (ImageView) findViewById(R.id.puzzle_make_pic);
        puzzle_make_edit = (EditText) findViewById(R.id.puzzle_make_edit);
        puzzle_make = (RelativeLayout) findViewById(R.id.puzzle_make);
        line_v1 = findViewById(R.id.line_v1);
        line_v2 = findViewById(R.id.line_v2);
        line_h1 = findViewById(R.id.line_h1);
        line_h2 = findViewById(R.id.line_h2);
        int h = UIHelper.getScreenWidth(PuzzleMakeActivity.this) - UIHelper.dip2px(PuzzleMakeActivity.this, 20);
        puzzle_make.setLayoutParams(new LinearLayout.LayoutParams(h, h));
        RelativeLayout.LayoutParams lpv1 = (RelativeLayout.LayoutParams) line_v1.getLayoutParams();
        lpv1.leftMargin = h / 3;
        RelativeLayout.LayoutParams lpv2 = (RelativeLayout.LayoutParams) line_v2.getLayoutParams();
        lpv2.leftMargin = h * 2 / 3;
        RelativeLayout.LayoutParams lph1 = (RelativeLayout.LayoutParams) line_h1.getLayoutParams();
        lph1.topMargin = h / 3;
        RelativeLayout.LayoutParams lph2 = (RelativeLayout.LayoutParams) line_h2.getLayoutParams();
        lph2.topMargin = h * 2 / 3;
    }

    private void initProgress() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_UP);
    }


    private void initData() {
        chuanpath = getIntent().getStringExtra("imagelocal");
        eventid = getIntent().getStringExtra("eventid");
        if (!chuanpath.contains("http")) {
            ImageLoader.getInstance().displayImage("file://" + Uri.parse(chuanpath), puzzle_make_pic);
        }
    }

    private String content = "";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.puzzle_make_back:
                finish();
                break;
            case R.id.puzzle_make_share:
                content = puzzle_make_edit.getText().toString();
                mProgressDialog.show();
                getTokenJieTu(content);
                break;
        }
    }

    private void getTokenJieTu(final String content) {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            mUpManager.put(chuanpath, UUID.randomUUID().toString() + ".png", resToken.getData().get(0).getToken(),
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {
                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        public void progress(String key, double percent) {
                                            if (percent == 1.0) {
                                                Make(content, key);
                                            }
                                        }
                                    }, null));
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private void Make(String content, String key) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("picture", key);
        mParam.put("content", content);
        StringRequest req = new StringRequest(getString(R.string.ynMakePuzzle))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        mProgressDialog.dismiss();
                        Log.i("xjs", "make===>" + s);
                        try {
                            JSONObject json = new JSONObject(s);
                            if (ReqUtils.isSuccess(json.optString("code"))) {
                                String encodePuzzleID = json.optJSONArray("data").optJSONObject(0).optString("encodePuzzleID");
                                String puzzleShareurl = getResources().getString(R.string.ynPuzzleShare) + encodePuzzleID
                                        + "&fromUserID=" + application.getCurID()
                                        + "&fromSpaceID=" + application.getCurGid()
                                        + "&fromEventID=" + eventid
                                        + "&port=App拼图分享";
                                String puzzleID = json.optJSONArray("data").optJSONObject(0).optString("puzzleID");
                                String puzzlePath = "/pages/pingtu/pingtu?id=" + puzzleID
                                        + "&fromUserID=" + application.getCurID()
                                        + "&fromSpaceID=" + application.getCurGid()
                                        + "&fromEventID=" + eventid
                                        + "&port=App拼图分享";
                                Intent intent = new Intent(PuzzleMakeActivity.this, PuzzleShareActivity.class);
                                intent.putExtra("title", "我用一张照片做了个拼图游戏，一起来玩！");
                                intent.putExtra("desc", "完成拼图，可以看看TA的神秘照片");
                                intent.putExtra("url", puzzleShareurl);
                                intent.putExtra("puzzleMinPath", puzzlePath);
                                startActivity(intent);
                                finish();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                        mProgressDialog.dismiss();
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        File ff = new File(chuanpath);
        if (ff != null && ff.exists()) {
            ff.delete();
        }
    }
}